<?php
namespace app\common\model;
use think\model\concern\SoftDelete;
use think\Paginator;

class BrandModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'brand';

    protected $json = ['content'];

    public function getContentAttr($value)
    {

        return self::getContent($value);
    }

    public static function getContent($value)
    {
        if(!is_array($value)){
            $value = json_decode($value,true);
        }

        if(empty($value)){
            return [];
        }

        if(app()->http->getName()!='admin' && !empty($value)){
            $data = [];
            foreach ($value as $item){
                $name = $item['name']??'';
                $content = explode("\r\n",$item['content']??'');
                $data[] = [
                    'name' =>$name,
                    'content' =>$content,
                ];
            }
            return $data;

        }
        return $value;
    }


    /**
     * 获取列表
     * @param array  $input_data
     * @throws
     * @return Paginator
     * */
    public static function getPageData(array $input_data = [])
    {
        $limit = $input_data['limit']??null;
        $where=[];
        if(app()->http->getName()!='admin'){
            $where[] = ['status','=',1];
        }
        $model =self::where($where)->order('sort asc');
        return $model->paginate($limit);
    }


    public static function handleSaveData(array $input_data = [])
    {
        if(empty($input_data['time'])) throw new \Exception('请输入时间');
        if(empty($input_data['img'])) throw new \Exception('请上传图片');
        (new self())->actionAdd($input_data);
    }



    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[

            'status'=>$this['status'],
            'sort'=>$this['sort'],
            'status_name'=>self::getPropInfo('fields_status',$this['status'],'name'),
            'update_time'=>$this['update_time'],

        ]);
    }

    public function apiNormalInfo()
    {
        return [
            'id'=>(string)$this['id'],
            'time'=>$this['time'],
            'img'=>$this['img'],
            'content'=>$this['content'],
            'url'=>$this['url'],
        ];
    }


    public function linkChild()
    {
        return $this->hasMany(self::class,'pid')->order('sort asc');
    }
}